<?php


namespace App\Web\Controller;

use App\Service\Crmapi as crm;
use App\Web\Facades\UserAuth;
use App\Web\Model\CaseFlow;
use App\Web\Model\CaseModel;
use App\Web\Model\CustomerAccount as AccountModel;
use App\Web\Service\RightCheck;
use EchoPHP\Facades\Db;
use EchoPHP\Http\Request;
use App\Web\Model\Project as ProjectModel;
use App\Web\Model\Customer as CustomerModel;
use EchoPHP\Validator\Validator;
use App\Web\Model\ProjectReport;

class Project extends Controller {

    public $rightCheck = [

    ];

    /**
     * 新建项目
     * @param $params ['subid'] 客户id
     * @param $params ['projectname'] 项目名称
     * @param $params ['crmnum'] crm项目编号
     * @param $params ['oprid'] 项目执行人数组
     * @param $params ['charger']  项目负责人id
     * @param $params ['tagcode'] 项目流程
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function add(Request $request) {
        $params = [
            'subid' => $request->getPost('subid/d'),
            'crmnum' => $request->getPost('crmnum'),
            'oprid' => $request->getPost('oprid'),
            'charger' => $request->getPost('charger'),
            'tagcode' => $request->getPost('tagcode'),
            'contactfield' => $request->getPost('contactfield', []),
            'chargeway' => $request->getPost('chargeway', [])//交互方式数组
        ];
        $projectModel = new ProjectModel();
        return $this->json($projectModel->add($params));
    }

    /**项目信息修改
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editCrmInfo(Request $request) {
        $params = [
            'projectid' => $request->getPost('projectid/d'),
            'crmnum' => $request->getPost('crmnum'),
        ];
        $projectModel = new ProjectModel();
        $result = $projectModel->editCrmInfo($params);
        return $this->json($result);
    }


    /**编辑项目状态
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editStatus(Request $request) {
        $projectId = $request->getPost('projectid/d', 0);
        $status = $request->getPost('status');//'01'开始，'02'暂停，'03'结束
        $projectModel = new ProjectModel();
        $result = $projectModel->editStatus($projectId, $status);
        return $this->json($result);
    }

    /**
     * 添加项目沟通表头
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addContactField(Request $request) {
        $projectId = $request->getPost('projectid', 0);
        $contactField = [
            'fieldname' => $request->getPost('fieldname'),
            'showname' => $request->getPost('showname'),
            'unit' => $request->getPost('unit'),
            'type' => $request->getPost('type'),
            'arguments' => $request->getPost('arguments', []),//['测试试'=>'测试试','测试试2'=>'测试试2'],//
            'issys' => $request->getPost('issys')
        ];
        $projectModel = new ProjectModel();
        $result = $projectModel->addContactField($projectId, $contactField);
        return $this->json($result);
    }

    /**
     * 修改项目沟通表头
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editContactField(Request $request) {
        $contactFieldId = $request->getPost('contactfieldid', 0);
        $contactField = [
            'fieldname' => $request->getPost('fieldname'),
            'showname' => $request->getPost('showname'),
            'unit' => $request->getPost('unit'),
            'type' => $request->getPost('type'),
            'arguments' => $request->getPost('arguments', []),
            'issys' => $request->getPost('issys')
        ];
//            [
//            'fieldname' => '测试修改',
//            'showname' => '测试修改',
//            'unit' => 100,
//            'type' => 233,
//            'arguments' => ['test'=>'test','xixi' => 'xixi'],
//        ];
        $projectModel = new ProjectModel();
        $result = $projectModel->editContactField($contactFieldId, $contactField);
        return $this->json($result);
    }

    /**
     * 删除项目 沟通表头
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteContactField(Request $request) {
        $contactFieldId = $request->getPost('contactfieldid', 0);
        $projectModel = new ProjectModel();
        $result = $projectModel->deleteContactField($contactFieldId);
        return $this->json($result);
    }

    /**
     * 删除交付方式
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteChargeWay(Request $request) {
        $chargeId = $request->getPost('chargeid', 0);
        $projectModel = new ProjectModel();
        $result = $projectModel->deleteChargeWay($chargeId);
        return $this->json($result);
    }

    /**
     * 删除交付方式下收费标准
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteChargeStandard(Request $request) {
        $chargeId = $request->getPost('chargeid', 0);
        $projectModel = new ProjectModel();
        $result = $projectModel->deleteChargeStandard($chargeId);
        return $this->json($result);
    }

    /**
     * 项目添加交付方式
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addChargeWay(Request $request) {
        $projectId = $request->getPost('projectid', 0);
        $chargeway = $request->getPost('chargeway', []); //新增的交付方式数组  [...,children=>[],...]
        $projectModel = new ProjectModel();
        $result = $projectModel->addChargeWay($projectId, $chargeway);
        return $this->json($result);
    }

    /**
     * 添加交付方式的收费标准
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addChargeStandard(Request $request) {
        $chargeId = $request->getPost('chargeid', 0);
        $standard = $request->getPost('standard', []);
        //$standard = ['chargetype'=>'d','standard'=>'d','salarytype'=>'d','salaryfrom'=>'555','salaryto'=>'666'];
        $projectModel = new ProjectModel();
        $result = $projectModel->addChargeStandard($chargeId, $standard);
        return $this->json($result);
    }

    /**
     * 修改项目交付方式
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editChargeWay(Request $request) {
        $chargeId = $request->getPost('chargeid', 0);
        $params = [
            'chargeway' => $request->getPost('chargeway'),
            'targetnum' => $request->getPost('targetnum'),
            'bindflow' => $request->getPost('bindflow')
        ];
        $projectModel = new ProjectModel();
        $result = $projectModel->editChargeWay($chargeId, $params);
        return $this->json($result);
    }

    /**
     * 修改项目交付方式的收费标准
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editChargeStandard(Request $request) {
        $chargeId = $request->getPost('chargeid', 0);
        $standard = $request->getPost('standard');
        $projectModel = new ProjectModel();
        $result = $projectModel->editChargeStandard($chargeId, $standard);
        return $this->json($result);
    }

    /**
     * 获取项目下定义的所有 沟通表头
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getContactFieldList(Request $request) {
        $projectId = $request->getParam('projectid', 0);
        $projectModel = new ProjectModel();
        $contactFieldList = $projectModel->getContactFieldList($projectId);
        return $this->json($contactFieldList);
    }

    /**
     * 获取项目下定义的所有 交付方式
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getChargeWayList(Request $request) {
        $projectId = $request->getParam('projectid', 0);
        $projectModel = new ProjectModel();
        $chargeWayList = $projectModel->getChargeWayList($projectId);
        return $this->json($chargeWayList);
    }

    //项目列表
    public function show(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);
        $params = [
            'subid' => $request->getParam('subid'),
            'subname' => $request->getParam('subname'),
            'projectname' => $request->getParam('projectname'),
        ];
        $projectModel = new ProjectModel();
        list($pageNum, $rowFrom, $rowTo) = $projectModel->paginationParameters($pageNum, $pageLimit);
        $count = $projectModel->myProject($params, 'count(1) as count');
        $projectList = [];
        if ($count) {
            $projectList = $projectModel->myProject($params, '', $rowFrom, $rowTo);
            $oprList = $projectModel->operatorList(array_column($projectList, 'projectid'));
            foreach ($projectList as $key => $project) {
                $projectList[$key]['opr'] = $oprList[$project['projectid']] ?? [];
            }
//            $projectList = (new ProjectReport())->fullReport($projectList);
        }
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'totalcount' => intval($count),
                'pagenum' => $pageNum,
                'projectlist' => $projectList,
            ]
        );
    }

    //项目详细信息
    public function detail(Request $request) {
        $projectId = $request->getParam('projectid');
        $projectModel = new ProjectModel();
        $projectInfo = $projectModel->detail($projectId);
        if (empty($projectInfo)) {
            $projectInfo = ['projectid' => '',
                'subid' => '',
                'subname' => '',
                'projectname' => '',
                'status' => '',
                'crmprojectnum' => '',
                'crmoperatorname' => '',
                'crmmanagername' => '',
                'crmprerevenue' => '',
                'crmdeliveryway' => '',
                'crmdeliverynum' => '',
                'crmfollowcontent' => ''];
        }
        return $this->json([
            'status' => true,
            'massage' => '获取成功',
            'projectinfo' => $projectInfo,
        ]);
    }

    public function getFlow(Request $request) {
        $projectId = $request->getParam('projectid');
        $projectModel = new ProjectModel();
        $result = $projectModel->chkGetRight($projectId);
        if (!$result) {
            return $this->json([
                'status' => false,
                'message' => '无权查看该信息',
                'flowlist' => [],
            ]);
        }
        $caseFlowModel = new CaseFlow();
        $result = $caseFlowModel->getProjectFlowFull($projectId);
        return $this->json([
            'status' => empty($result) ? false : true,
            'message' => empty($result) ? '未定义流程标签' : '获取成功',
            'flowlist' => $caseFlowModel->transFlowToNotAssoc($result),
        ]);
    }

    public function editFlow(Request $request) {
        $params = [
            'projectid' => $request->getPost('projectid/d'),
            'tagcode' => $request->getPost('tagcode'),
        ];
        $projectModel = new ProjectModel();
        $result = $projectModel->editFlow($params);
        return $this->json($result);
    }


    //展示执行人
    public function showOperator(Request $request) {
        $projectId = $request->getParam('projectid');
        $projectModel = new projectModel();
        return $this->json([
            'status' => true,
            'message' => '查询成功',
            'oprlist' => $projectModel->showOperator($projectId)
        ]);
    }

    //添加执行人
    public function addOperator(Request $request) {
        $projectId = $request->getPost('projectid');
        $oprId = $request->getPost('oprid');
        $projectModel = new ProjectModel();
        $result = $projectModel->addOperator($projectId, $oprId);
        return $this->json($result);

    }

    //删除执行人
    public function delOperator(Request $request) {
        $projectId = $request->getPost('projectid');
        $oprId = $request->getPost('oprid');
        $projectModel = new ProjectModel();
        $result = $projectModel->delOperator($projectId, $oprId);
        return $this->json($result);
    }

    public function transferCharger(Request $request) {
        $projectId = $request->getPost('projectid');
        $oprId = $request->getPost('oprid');
        $projectModel = new ProjectModel();
        if (!$projectModel->chkEditRight($projectId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该项目']);
        }
        $result = $projectModel->transferCharger($oprId, $projectId);
        return $this->json(['status' => $result, 'message' => $result ? '修改成功' : '操作失败']);
    }

    /**获取CRM项目信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function crmProjectDetail(Request $request) {
        $crmNum = $request->getParam('crmnum');
        $subId = $request->getParam('subid');
        $sql = 'select crmsubid from CustomerSub where subid = ?';
        $crmSubId = Db::selectOne($sql, [$subId]);
        if (!$crmSubId) {
            return $this->json(['status' => false, 'message' => '操作失败', 'validateFailure' => ['subid' => '客户id非法']]);
        }
        $model = new ProjectModel();
        $crmExist = $model->checkCrmExist($crmNum);
        if (!$crmExist['status']){
            return $this->json($crmExist);
        }
        $crmService = new crm();
        $result = $crmService->getCrmProjectInfo($crmNum);
        if (!$result || $crmSubId['crmsubid'] != $result['accsubid']) {
            return $this->json(['status' => false, 'message' => '操作失败', 'validateFailure' => ['crmnum' => 'crm信息获取失败']]);
        }
        return $this->json([
            'status' => true,
            'message' => '查找成功',
            'crmprojectinfo' => $result
        ]);
    }

    public function crmProjectList(Request $request) {
        $subId = $request->getParam('subid');
        $projectModel = new ProjectModel();
        $result = $projectModel->getAllCrmProjectBySubId($subId);
        return $this->json([
            'status' => true,
            'message' => '查找成功',
            'crmprojectinfo' => $result
        ]);
    }

    public function crmInfoSync(Request $request) {
        $projectId = $request->getParam('projectid');
        $projectModel = new ProjectModel();
        $user = UserAuth::getLoginInfo();
        $result = $projectModel->crmInfoSync($projectId, $user);
        return $this->json($result);
    }

    /**
     * 项目详情页添加客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addInterviewerInProject(Request $request) {
        $params = [
            'email' => $request->getParam('email'),
            'projectid' => $request->getParam('projectid'),
            'cname' => $request->getParam('cname'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer')
        ];
        if (empty($params['projectid'])) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => '项目id不能为空'
            ]);
        }
        $accountModel = new AccountModel();
        $checkResult = $accountModel->addContactorDataCheck($params);
        if ($checkResult['status'] == false) {
            return $this->json($checkResult);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $sql = 'select subid from Project where projectid = ?';
        $var = [$params['projectid']];
        $projectInfo = Db::selectOne($sql,$var);
        if (empty($projectInfo)) {
            return $this->json(['status' => false, 'message' => '项目信息错误']);
        }
        //是否是项目负责人
        $projectModel = new ProjectModel();
        $checkResult1 = $projectModel->chkEditRight($params['projectid']);
        $customerModel = new CustomerModel();
        $checkResult2 = $customerModel->chkEditSubRight($projectInfo['subid']);
        if(!$checkResult1 && !$checkResult2) {
            return $this->json(['status' => false, 'message' => '您无权新增客户联系人']);
        }

        $params['subid'] = $projectInfo['subid'];
        $result = $accountModel->add($params);
        return $this->json($result);
    }

    /**
     * 项目详情页编辑客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editCustomerAccount(Request $request) {
        $params = [
            'accountid' => $request->getParam('accountid'),
            'email' => $request->getParam('email'),
            'cname' => $request->getParam('cname'),
            'projectid' => $request->getParam('projectid'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer',0)
        ];
        $rule = [
            'accountid|客户账户id' => [
                'required', 'number'
            ],
            'email|客户账户邮箱' => [
                'required', 'email'
            ],
            'projectid|项目id' => [
                'required', 'number'
            ],
            'cname|客户账户名称' => [
                'required', 'maxLength' => 50
            ],
            'mobilephone|面试官手机' => [
                'required', 'minLength' => 7, 'maxLength' => 19
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ]);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $sql = 'select subid from Project where projectid = ?';
        $var = [$params['projectid']];
        $projectInfo = Db::selectOne($sql,$var);
        if (empty($projectInfo)) {
            return $this->json(['status' => false, 'message' => '项目信息错误']);
        }
        //是否是项目负责人
        $projectModel = new ProjectModel();
        $checkResult1 = $projectModel->chkEditRight($params['projectid']);
        $customerModel = new CustomerModel();
        $checkResult2 = $customerModel->chkEditSubRight($projectInfo['subid']);
        if(!$checkResult1 && !$checkResult2) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $params['subid'] = $projectInfo['subid'];
        return $this->json((new AccountModel())->edit($params));
    }

    /**
     * 项目详情页删除客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteCustomerAccount(Request $request) {
        $accountId = $request->getParam('accountid');
        $projectId = $request->getParam('projectid');
        $sql = 'select subid from Project where projectid = ?';
        $var = [$projectId];
        $projectInfo = Db::selectOne($sql,$var);
        if (empty($projectInfo)) {
            return $this->json(['status' => false, 'message' => '项目信息错误']);
        }
        //是否是项目负责人
        $projectModel = new ProjectModel();
        $checkResult1 = $projectModel->chkEditRight($projectId);
        $customerModel = new CustomerModel();
        $checkResult2 = $customerModel->chkEditSubRight($projectInfo['subid']);
        if(!$checkResult1 && !$checkResult2) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $subId = $projectInfo['subid'];
        $result = (new AccountModel())->lock($accountId, $subId);
        return $this->json(
            [
                'status' => $result == 1,
                'message' => $result == 1 ? '修改成功' : '修改失败',
            ]
        );
    }

    /**
     * 项目详情页删除客户联系人时判断是否已被职位绑定
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteCheck(Request $request) {
        $accountId = $request->getParam('accountid');
        $projectId = $request->getParam('projectid');
        $sql = 'select subid from Project where projectid = ?';
        $var = [$projectId];
        $projectInfo = Db::selectOne($sql,$var);
        if (empty($projectInfo)) {
            return $this->json(['status' => false, 'message' => '项目信息错误']);
        }
        //是否是项目负责人
        $projectModel = new ProjectModel();
        $checkResult1 = $projectModel->chkEditRight($projectId);
        $customerModel = new CustomerModel();
        $checkResult2 = $customerModel->chkEditSubRight($projectInfo['subid']);
        if(!$checkResult1 && !$checkResult2) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $subId = $projectInfo['subid'];
        $sql = 'select 1 from CaseContacter where accountid = ? and subid = ? and status = ?';
        $var = [$accountId,$subId,'01'];
        $result = Db::selectOne($sql,$var);
        if (!empty($result)) {
            return $this->json([
                'status' => 1,
                'message' => '该联系人已被交易公司下的职位绑定，确定删除吗？'
            ]);
        }
        return $this->json([
            'status' => 2,
            'message' => '校验成功'
        ]);
    }
}